#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sub license,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

import numpy as np
from LCSolverBase import LCSolverBase
from scipy import diag


class Sor(LCSolverBase):

    """
    Synopsis:
    ---------
      The method is guaranty to converge for symmetric matrices and diagonal dominant matrices

      Solves   z^T(Az+b) = 0
                   Az+b >= 0
                   z    >= 0

      SOR          approximate the solution of the linear system Ax = b by applying
                   the SOR method (successive over-relaxation)

           calling sequences:
                   x = sor ( M, b, xold, omega, TOL, Nmax )
                   sor ( M, b, xold, omega, TOL, Nmax )

           inputs:
                   M       coefficient matrix for linear system - must be a
                           square matrix, sparse or dense
                   b       right-hand side vector for linear system
                   xold    vector containing initial guess for solution of
                           linear system
                   omega   relaxation parameter
                   TOL     convergence tolerance - applied to maximum norm of
                           difference between successive approximations
                   NMax    maximum number of iterations to be performed

           output:
                   x       approximate solution of linear system

        Reference:
            [0] S. Ikonen and J. Toivanen. Efficient numerical methods for pricing American op-
            tions under stochastic volatility.
    """

    __init__ = ['m_omega']

    def __init__(self, M, b, method=None, omega=None, constraint=None):
        LCSolverBase.__init__(self, M, b, method, constraint)
        assert omega == None or (0 < omega and omega <= 2)
        self.m_omega = omega

    def _relaxationParameter(self):
        M = self.get_matrix()
        diags = diag(M)
        rho = 0.
        (nRows, cols) = M.shape
        for i in range(nRows):
            row = abs(M[i, :])
            row[i] = 0.
            assert 0 != diags[i]
            rho = max(rho, sum(row) / diags[i])
        return 2. / (1. + np.sqrt(1. - rho ** 2))  # Ref [0]

    def solve_lc_tridia(self):
        if None == self.m_omega:
            self.omega = self._relaxationParameter()

        M = self.get_matrix()
        diag0 = diag(M)
        (diag1, diag_1) = (diag(M, 1), diag(M, -1))

        b = self.get_rhs()
        xn = self.solution()

        const = self.get_constraint()
        if 'pSor' == self.get_lcp_solver_type():
            assert const != None
        else:
            const = xn

        omega = self.m_omega
        xp = xn
        xr = np.zeros(b.shape)  # USE INSIDE LOOP
        dim = diag0.size

        error = .10
        while error > self.get_tolerance():
            xr = xn.copy()
            xn[0] = (1. - omega) * xp[0] + omega * (b[0] - diag1[0]
                    * xp[1]) / diag0[0]
            xn[0] = max(xn[0], const[0])
            xn[1] = (1. - omega) * xp[1] + omega * (b[1] - diag_1[0]
                    * xp[0] - diag1[1] * xp[2]) / diag0[1]
            xn[1] = max(xn[1], const[1])

            for i in np.arange(2, dim - 2):
                tmp = diag_1[i - 1] * xp[i - 1] + diag1[i] * xp[i + 1]
                xn[i] = (1. - omega) * xp[i] + omega * (b[i] - tmp) \
                    / diag0[i]
                xn[i] = max(xn[i], const[i])

            tmp = diag_1[dim - 3] * xp[-3] + diag1[dim - 2] * xp[-1]
            xn[-2] = (1. - omega) * xp[-2] + omega * (b[-2] - tmp) \
                / diag0[-2]
            xn[-2] = max(xn[-2], const[-2])

            tmp = diag_1[dim - 2] * xp[-2]
            xn[-1] = (1. - omega) * xp[-1] + omega * (b[-1] - tmp) \
                / diag0[-1]
            xn[-1] = max(xn[-1], const[-1])
            error = np.linalg.norm((xr - xn).flatten())

    def solve_lc_pendia(self):
        if None == self.m_omega:
            self.omega = self._relaxationParameter()

        M = self.get_matrix()
        diag0 = diag(M)
        (diag1, diag2) = (diag(M, 1), diag(M, 2))
        (diag_1, diag_2) = (diag(M, -1), diag(M, -2))

        b = self.get_rhs()
        xn = self.solution()

        const = self.get_constraint()
        if 'pSor' == self.get_lcp_solver_type():
            assert const != None
        else:
            const = xn

        omega = self.m_omega
        xp = xn
        xr = np.zeros(b.shape)  # USE INSIDE LOOP
        dim = diag0.size

        error = .10
        while error > self.get_tolerance():
            xr = xn.copy()
            xn[0] = (1. - omega) * xp[0] + omega * (b[0] - diag1[0]
                    * xp[1] - diag2[0] * xp[2]) / diag0[0]
            xn[0] = max(xn[0], const[0])
            xn[1] = (1. - omega) * xp[1] + omega * (b[1] - diag_1[0]
                    * xp[0] - diag1[1] * xp[2] - diag2[1] * xp[3]) \
                / diag0[1]
            xn[1] = max(xn[1], const[1])

            for i in np.arange(2, dim - 2):
                tmp = diag_2[i - 2] * xp[i - 2] + diag_1[i - 1] * xp[i
                        - 1] + diag1[i] * xp[i + 1] + diag2[i] * xp[i
                        + 2]
                xn[i] = (1. - omega) * xp[i] + omega * (b[i] - tmp) \
                    / diag0[i]
                xn[i] = max(xn[i], const[i])

            tmp = diag_2[dim - 4] * xp[-4] + diag_1[dim - 3] * xp[-3] \
                + diag1[dim - 2] * xp[-1]
            xn[-2] = (1. - omega) * xp[-2] + omega * (b[-2] - tmp) \
                / diag0[-2]
            xn[-2] = max(xn[-2], const[-2])

            tmp = diag_2[dim - 3] * xp[-3] + diag_1[dim - 2] * xp[-2]
            xn[-1] = (1. - omega) * xp[-1] + omega * (b[-1] - tmp) \
                / diag0[-1]
            xn[-1] = max(xn[-1], const[-1])
            error = np.linalg.norm((xr - xn).flatten())

    def solve(self):
        if None == self.m_omega:
            self.omega = self._relaxationParameter()

        if 5 == self.get_matrix_attr():
            return self.solve_lc_pendia()

        if 3 == self.get_matrix_attr():
            return self.solve_lc_tridia()

        b = self.get_rhs()
        M = self.get_matrix()
        xn = self.solution()

        const = self.get_constraint()
        if 'pSor' == self.get_lcp_solver_type():
            assert const != None
        else:
            const = xn

        omega = self.m_omega
        xp = xn
        xr = np.zeros(b.shape)  # USE INSIDE LOOP
        error = .10
        while error > self.get_tolerance():
            xr = xn.copy()
            for i in np.arange(xp.size):
                xn[i] = (1. - omega) * xp[i] + omega * (xp[i] + (b[i]
                        - np.dot(M[i, :], xp)) / M[i, i])
                xn[i] = max(xn[i], const[i])
            error = np.linalg.norm((xr - xn).flatten())


